package com.vesus.springbootwebsocket.intercept;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.util.HashMap;
import java.util.Map;

/**
 * 通道拦截器
 */
public class WsChatInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if (raw instanceof Map) {

                Object token = ((Map) raw).get("token");
                System.out.println("------------");
                System.out.println(token);


            }
        }
        if (StompCommand.SEND.equals(accessor.getCommand())) {
            accessor.setMessage("ddddddddd");


            Map map = new HashMap();
            map.put("aaa", "111");
            accessor.setSessionAttributes(map);
        }
        return message;
    }
}
